<template>
  <div class="clearfix">
    <a-upload
      name="file"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      @change="handleChange"
      :custom-request="uploadUP"
    >
      <div class="img-box" v-if="imageUrl"><img class="img" :src="imageUrl" /></div>
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">Upload</div>
      </div>
    </a-upload>
  </div>
</template>
<script lang="ts" setup>
import { ref, watchEffect } from 'vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import http from '@/api/http'
import { message } from 'ant-design-vue'
import type { UploadChangeParam } from 'ant-design-vue'

const loading = ref<boolean>(false)
const emit = defineEmits(['change'])
const prop = defineProps<{ value: string; folder?: string }>()
const imageUrl = ref(prop.value)

const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!')
  }
  return isJpgOrPng && isLt2M
}

const handleChange = (info: UploadChangeParam) => {
  if (info.file.status === 'uploading') {
    loading.value = true
    return
  }
  if (info.file.status === 'done') {
    return
  }
  if (info.file.status === 'error') {
    loading.value = false
    message.error('upload error')
  }
}

type UploadImageData = { key: string; url: string; bucket: string }

const uploadUP = async ({ file }: { file: File }) => {
  try {
    loading.value = true
    const formData = new FormData()
    formData.append('file', file)
    const folder = prop.folder
    const resp = await http.post<FormData, UploadImageData>('/admin/common/upload-image', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      params: folder ? { folder } : undefined,
    })
    if (resp.code === 200 && resp.data) {
      imageUrl.value = resp.data.url
      emit('change', imageUrl.value)
      loading.value = false
    } else {
      loading.value = false
      message.error(resp.message || '上传失败')
    }
  } catch {
    loading.value = false
    message.error('上传失败')
  }
}

watchEffect(() => {
  imageUrl.value = prop.value
  loading.value = false
})
</script>
<style lang="stylus" scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
  overflow hidden;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.img-box{
  width: 100px;
  height: 100px;
  overflow hidden;
  display flex
  justify-content center
  align-items center
}
.img{
   width: 100px;
}
</style>
